<?php


    /**
    * @subpackage Controllers
    * @package Modules
    * @author Daniel Huynh
    */

    class quizzesController extends  expController {
        public $basemodel_name = 'photo';
        //    public $useractions = array(
        //        'showall'=>'Gallery',
        //        'slideshow'=>'Slideshow',
        //        //'showall_tags'=>"Tag Categories"
        //    );
        public $remove_configs = array(
        'comments',
        'ealerts',
        'facebook',
        'files',
        'pagination',  // we need to customize it in this module?
        'rss',
        'twitter',
        );  // all options: ('aggregation','categories','comments','ealerts','facebook','files','pagination','rss','tags','twitter',)

        static function displayname() { return gt("Music Album"); }
        static function description() { return gt("Displays and manages music."); }
        static function isSearchable() { return true; }

        public function showall() {
            expHistory::set('viewable', $this->params);
            $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;
            if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {
                $limit = '0';
            }
            $order = isset($this->config['order']) ? $this->config['order'] : "rank";
            $page = new expPaginator(array(
            'model'=>'photo',
            'where'=>$this->aggregateWhereClause(),
            'limit'=>$limit,
            'order'=>$order,
            'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],
            'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),
            'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),
            'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
            gt('Title')=>'title'
            ),
            ));

            assign_to_template(array(
            'page'=>$page,
            ));
        }

        public function get_all_json()
        {
            /*
            *Quizzes types 
            * 0. Trắc nghiệm chọn 1
            * 1. Trắc nghiệm chọn nhiều
            * 2. Trả lời ngắn <20 ky tu
            * 3. Trả lời nhanh
            * 
            */
            global $user,$db;
            $quizzes=null;
            $data=null;
            if($user->isLoggedIn())
            {
                $page=isset($_REQUEST['page'])?$_REQUEST['page']:1;
                $limit=isset($_REQUEST['limit'])?$_REQUEST['limit']:20;
                //$page=isset($_REQUEST['page'])?$_REQUEST['page']:1;
                $total=$db->countObjects('quiz');
                $start = $limit*$page - $limit;
                if( $count > 0 && $limit > 0) { 
                    $total_pages = ceil($total/$limit); 
                } else { 
                    $total_pages = 0; 
                } 

                if($user->isAdmin())
                {
                    $quizzes=$db->selectObjects('quiz_collect',"1=1 LIMIT $start,$limit");
                }
                else
                {
                    $quizzes=$db->selectObjects('quiz_collect','make_by='.$user->id.' LIMIT 0,20');
                }
                $data->total=$total_pages;
                $data->records=$total;
                $data->page=$page;
                $data->data=$quizzes;
            }
            else
            {

            }
            echo json_encode($quizzes);

        }

        public function list_all()
        {
            global $user,$db;
            $quizzes=null;
            if($user->isLoggedIn())
            {

            }
            else
            {

            }
            assign_to_template(array(
            'record'=>$record
            ));

        }

        public function post_string()
        {
            global $db,$user;
            $_id=$_REQUEST['quiz_id']>0?(int)$_REQUEST['quiz_id']:0;
            $quiz_coll=null;
            if($_id)
                $quiz_coll = $db->selectObject('quiz_collect','id='.$_id);
                else
                $quiz_coll= new Quiz_collect();
            $quiz=new quiz();            
            $quiz_coll->make_by=$user->id;
            $quiz_coll->default_type=(int)$_REQUEST['default_type'];
            $quiz_coll->description=$_REQUEST['description'];
            $quiz_coll->name=$_REQUEST['name'];
            $quiz_coll->name=$_REQUEST['name']; 
            if($_id)
                $db->updateObject($quiz_coll,'quiz_collect');
            else
                $quiz_coll->id=$db->insertObject($quiz_coll,'quiz_collect');           
            $result=$quiz->post_quiz_from_string($_REQUEST['collect_content'],$quiz_coll,$_id);
            if($result==true)
            {
                echo 'success';
            }
            else
                echo $result;


        } 

        public function control_all()
        {

        }
        public function quiz_edit()
        {
            global $user,$db;
            $new=true;
            $string="";
            if($user->isLoggedIn())
            if(isset($_REQUEST['quiz']))
            {
                $new=false;
                $_id=(int)$_REQUEST['quiz'];
                ///Generral
                $colect_data=$db->selectObject('quiz_collect','id='.$_id.' AND make_by='.$user->id);
                $quiz_data=$db->selectObjects('quiz','collect_id='.$_id.' AND make_by='.$user->id,'create_on DESC');
                foreach($quiz_data as $k=>$quiz)
                {
                    $string.=$k>0?'<hr>':'';
                    $string.=QUIZ_NEW.$quiz->content.' ';
                    $string.=($quiz->point?QUIZ_POINT.$quiz->point:'');
                    $string.=($quiz->diff?QUIZ_DIFF.$quiz->diff:'');
                    $string.='<br> ';
                    $ans_array=json_decode($quiz->ans);
                    foreach($ans_array as $ans_k=>$ans)
                    {
                        if($ans_k+1==$quiz_data->right)
                        {
                            $string.=QUIZ_ANS.$ans.'<br>'.QUIZ_RIGHT;
                        }
                        else
                        {
                            $string.=QUIZ_ANS.$ans.'<br>';
                        }
                    }
                }
               
                
            }
             assign_to_template(array(
                'quiz_str'=>$string,
            'new'=>$new,
            'coll'=>$colect_data
            ));
        }

        function show() {
            global $db;

            expHistory::set('viewable', $this->params);

            // figure out if we're looking this up by id or title
            $id = null;
            if (isset($this->params['id'])) {
                $id = $this->params['id'];
            } elseif (isset($this->params['title'])) {
                $id = $this->params['title'];
            }
            $record = new photo($id);
            $where = $this->aggregateWhereClause();
            //        $maxrank = $db->max($this->model_table,'rank','',$where);
            //
            //        $record->next = $db->selectValue($this->model_table,'sef_url',$where." AND rank=".($record->rank+1));
            //        $record->prev = $db->selectValue($this->model_table,'sef_url',$where." AND rank=".($record->rank-1));
            //
            //        if ($record->rank==$maxrank) {
            //            $where = $where." AND rank=1";
            //            $record->next = $db->selectValue($this->model_table,'sef_url',$where);
            //        }
            //
            //        if ($record->rank==1) {
            //            $where = $where." AND rank=".$maxrank;
            //            $record->prev = $db->selectValue($this->model_table,'sef_url',$where);
            //        }
            $record->addNextPrev($where);

            //        $config = expUnserialize($db->selectValue('expConfigs','config',"location_data='".$record->location_data."'"));
            $config = expConfig::getConfig($record->location_data);

            assign_to_template(array(
            'record'=>$record,
            'imgnum'=>$record->rank,
            'imgtot'=>count($record->find('all',$this->aggregateWhereClause())),
            //            "next"=>$next,
            //            "previous"=>$prev,
            'config'=>$config
            ));
        }



        public function showall_tags() {
            $images = $this->image->find('all');
            $used_tags = array();
            foreach ($images as $image) {
                foreach($image->expTag as $tag) {
                    if (isset($used_tags[$tag->id])) {
                        $used_tags[$tag->id]->count += 1;
                    } else {
                        $exptag = new expTag($tag->id);
                        $used_tags[$tag->id] = $exptag;
                        $used_tags[$tag->id]->count = 1;
                    }

                }
            }

            assign_to_template(array(
            'tags'=>$used_tags
            ));
        }           

        public function update() {

            //populate the alt tag field if the user didn't
            if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];

            // call expController update to save the image
            parent::update();
        }

        public function multi_add() {
            //        global $db;

            //        $tags = $db->selectObjects('expTags', '1', 'title ASC');
            //        $taglist = '';
            //        foreach ($tags as $tag) {
            //            $taglist .= "'" . $tag->title . "',";
            //        }
            $taglist = expTag::getAllTags();
            $modelname = $this->basemodel_name;
            assign_to_template(array(
            //            'record'     => $record,
            'table'      => $this->$modelname->tablename,
            //            'controller' => $this->params['controller'],
            'taglist'    => $taglist
            ));
        }

        public function multi_update() {
            global $db;

            if (!empty($this->params['expFile'])) {
                if (!empty($this->params['title'])) {
                    $prefix = $this->params['title'] . ' - ';
                } else {
                    $prefix = '';
                }
                $params = array();
                //check for and handle tags
                if (array_key_exists('expTag', $this->params)) {
                    $tags = explode(",", trim($this->params['expTag']));

                    foreach ($tags as $tag) {
                        if (!empty($tag)) {
                            $tag = strtolower(trim($tag));
                            $tag = str_replace('"', "", $tag); // strip double quotes
                            $tag = str_replace("'", "", $tag); // strip single quotes
                            $expTag = new expTag($tag);
                            if (empty($expTag->id)) $expTag->update(array('title' => $tag));
                            $params['expTag'][] = $expTag->id;
                        }
                    }
                }

                //check for and handle cats
                if (array_key_exists('expCat', $this->params) && !empty($this->params['expCat'])) {
                    $catid = $this->params['expCat'];
                    $params['expCat'][] = $catid;
                }
                foreach ($this->params['expFile'] as $fileid) {
                    $params['expFile'][0] = new expFile($fileid);
                    if (!empty($params['expFile'][0]->id)) {
                        $photo = new photo();
                        $photo->expFile = $params['expFile'];
                        $loc = expCore::makeLocation("photo",$this->params['src']);
                        $photo->location_data = serialize($loc);
                        //                $photo->body = $gi['description'];
                        //                $photo->alt = !empty($gi['alt']) ? $gi['alt'] : $photo->title;
                        $filename = pathinfo($params['expFile'][0]->filename);
                        $photo->title = $prefix . $filename['filename'];
                        if (!empty($params['expTag'])) {
                            $photo->expTag = $params['expTag'];
                        }
                        if (!empty($params['expCat'])) {
                            $photo->expCat = $params['expCat'];
                        }
                        $photo->update($params);  // save gallery name as category
                    }
                }
                $this->addContentToSearch();
            }
            expHistory::back();
        }

    }

?>
